// myself/pages/train-manage/choose-cover/chooseCover.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    range:[],
    index:0,
    classify:[],
    imageClassify: '',
    fileType: '',
    list: [],
    selectedImg: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "更换图片",
    })
    this.setData({
      imageClassify: options.type,
      fileType: options.fileType
    })
    this.getClassify()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
    const classifId = this.data.classify[this.data.index].id
    this.getList({groupId:classifId})
  },
  getClassify() {
    app.api.post({
      url: 'image_group_getAll',
      data: {fileType: this.data.fileType}
    }).then(res => {
      console.log(res,'======');
      const arr = res || []
      const groupId = arr[0]?arr[0].id:''
      this.getList({groupId:groupId})
      const range = arr.reduce((p,c)=>{
        p.push(c.name)
        return p
      },[])
      this.setData({
        range: range || [],
        classify:res || []
      })
    })
  },
  getList (params) {
    // const { imageClassify } = this.data
    app.api.post({
      url: 'image_query',
      data: {
        pageSize:999,
        currentPage:1,
        ...params
      }
    }).then(res => {
      console.log(res,'======');
      this.setData({
        list: res.list || []
      })
    })
  },
  selectImg (e) {
    const { item } = e.currentTarget.dataset
    const { selectedImg } = this.data
    this.setData({
      selectedImg: item.resourceId === selectedImg.resourceId ? {} : item
    })
  },
  submit () {
    const { id, url } = this.data.selectedImg
    if(!id){
      wx.showToast({
        title: '请选择图片',
      })
      return
    }
    const img = {
      resourceId: id,
      url: url
    }
    if (this.data.imageClassify === 'cover') {
      app.globalData.coverImg = img
    } else {
      app.globalData.detailImg = img
    }
    app.globalData.dataUpdata = 'pending'
    wx.navigateBack()
  }
})